package de.koller.million.card.frame.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class NewsModel implements ListModel<NewsEntry> {

	public final int numberOfNews;
	private final List<NewsEntry> entries = new ArrayList<>();
	private final Set<ListDataListener> listeners = new HashSet<>();
	
	public NewsModel( int numberOfNews ) {
		this.numberOfNews = numberOfNews;
	}
	
	public void publish( NewsEntry entry ) {
		entries.add( 0, entry );
		while( entries.size() > numberOfNews )
			entries.remove( entries.size()-1 );
		
		for( ListDataListener i : listeners )
			i.contentsChanged( new ListDataEvent( this, ListDataEvent.CONTENTS_CHANGED, 0, numberOfNews ) );
	}
	
	@Override
	public void addListDataListener( ListDataListener l ) {
		listeners.add( l );
	}

	@Override
	public NewsEntry getElementAt( int index ) {
		if( index >= entries.size() )
			return null;
		else
			return entries.get( index );
	}

	@Override
	public int getSize() {
		return numberOfNews;
	}

	@Override
	public void removeListDataListener( ListDataListener l ) {
		listeners.remove( l );
	}
	
}
